// pages/venue/list.js
Page({
  data: {
    venues: [],
    venueTypes: [
      { id: 0, name: '全部' },
      { id: 1, name: '棋牌室' },
      { id: 2, name: '台球室' },
      { id: 3, name: 'KTV' }
    ],
    selectedType: 0,
    sortOptions: [
      { id: 'default', name: '默认排序' },
      { id: 'distance', name: '距离优先' },
      { id: 'rating', name: '评分优先' },
      { id: 'price', name: '价格优先' }
    ],
    selectedSort: 'default',
    keyword: '',
    loading: true,
    latitude: null,
    longitude: null,
    currentCity: '北京市',
    couponId: null
  },

  onLoad: function(options) {
    // 如果从首页点击某个类型进入，设置选中的类型
    if (options.typeId) {
      this.setData({
        selectedType: parseInt(options.typeId)
      });
    }
    
    // 检查是否有传入优惠券ID
    if (options.coupon_id) {
      this.setData({
        couponId: options.coupon_id
      });
    }
    
    // 获取当前选择的城市
    const currentCity = wx.getStorageSync('currentCity') || '北京市';
    this.setData({
      currentCity: currentCity
    });
    
    // 获取用户位置
    this.getUserLocation();
    
    // 加载场馆数据
    this.loadVenues();
  },
  
  // 点击选择城市
  onTapSelectCity: function() {
    wx.navigateTo({
      url: '/pages/venue/city',
      events: {
        // 监听城市选择页面返回的事件
        citySelected: (data) => {
          this.setData({
            currentCity: data.city,
            loading: true
          });
          this.loadVenues();
        }
      }
    });
  },
  
  // 获取用户位置
  getUserLocation: function() {
    wx.getLocation({
      type: 'gcj02',
      success: res => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        this.loadVenues();
      },
      fail: () => {
        // 如果获取位置失败，也加载场馆数据
        this.loadVenues();
      }
    });
  },
  
  // 加载场馆数据
  loadVenues: function() {
    // 模拟数据，实际项目中应该从服务器获取
    const allVenues = [
      {
        id: 1,
        name: '欢乐棋牌室',
        address: '北京市海淀区中关村大街1号',
        distance: '0.5km',
        type: '棋牌室',
        typeId: 1,
        rating: 4.8,
        price: '30元/小时起',
        imageUrl: '/images/venue/venue1.jpg',
        facilities: ['免费WiFi', '空调', '休息区'],
        openTime: '10:00-22:00'
      },
      {
        id: 2,
        name: '星牌台球俱乐部',
        address: '北京市海淀区中关村大街2号',
        distance: '0.8km',
        type: '台球室',
        typeId: 2,
        rating: 4.6,
        price: '40元/小时起',
        imageUrl: '/images/venue/venue2.jpg',
        facilities: ['免费WiFi', '空调', '休息区', '餐饮服务'],
        openTime: '11:00-23:00'
      },
      {
        id: 3,
        name: '麦乐迪KTV',
        address: '北京市海淀区中关村大街3号',
        distance: '1.2km',
        type: 'KTV',
        typeId: 3,
        rating: 4.7,
        price: '100元/小时起',
        imageUrl: '/images/venue/venue3.jpg',
        facilities: ['免费WiFi', '空调', '酒水服务'],
        openTime: '12:00-02:00'
      },
      {
        id: 4,
        name: '聚友棋牌',
        address: '北京市朝阳区建国路5号',
        distance: '3.5km',
        type: '棋牌室',
        typeId: 1,
        rating: 4.9,
        price: '35元/小时起',
        imageUrl: '/images/venue/venue4.jpg',
        facilities: ['免费WiFi', '空调', '休息区', '餐饮服务'],
        openTime: '10:00-22:00'
      },
      {
        id: 5,
        name: '乐动台球',
        address: '北京市朝阳区建国路6号',
        distance: '3.8km',
        type: '台球室',
        typeId: 2,
        rating: 4.7,
        price: '45元/小时起',
        imageUrl: '/images/venue/venue5.jpg',
        facilities: ['免费WiFi', '空调', '休息区'],
        openTime: '10:00-23:00'
      },
      {
        id: 6,
        name: '好声音KTV',
        address: '北京市朝阳区建国路7号',
        distance: '4.2km',
        type: 'KTV',
        typeId: 3,
        rating: 4.8,
        price: '120元/小时起',
        imageUrl: '/images/venue/venue6.jpg',
        facilities: ['免费WiFi', '空调', '酒水服务', 'VIP包间'],
        openTime: '12:00-02:00'
      }
    ];
    
    // 根据筛选条件过滤场馆
    let filteredVenues = allVenues;
    
    // 按类型筛选
    if (this.data.selectedType !== 0) {
      filteredVenues = filteredVenues.filter(venue => venue.typeId === this.data.selectedType);
    }
    
    // 按关键词搜索
    if (this.data.keyword) {
      const keyword = this.data.keyword.toLowerCase();
      filteredVenues = filteredVenues.filter(venue => 
        venue.name.toLowerCase().includes(keyword) || 
        venue.address.toLowerCase().includes(keyword) ||
        venue.type.toLowerCase().includes(keyword)
      );
    }
    
    // 排序
    switch (this.data.selectedSort) {
      case 'distance':
        filteredVenues.sort((a, b) => {
          const distA = parseFloat(a.distance.replace('km', ''));
          const distB = parseFloat(b.distance.replace('km', ''));
          return distA - distB;
        });
        break;
      case 'rating':
        filteredVenues.sort((a, b) => b.rating - a.rating);
        break;
      case 'price':
        filteredVenues.sort((a, b) => {
          const priceA = parseInt(a.price.match(/\d+/)[0]);
          const priceB = parseInt(b.price.match(/\d+/)[0]);
          return priceA - priceB;
        });
        break;
      default:
        // 默认排序，保持原顺序
        break;
    }
    
    this.setData({
      venues: filteredVenues,
      loading: false
    });
  },
  
  // 切换场馆类型
  onTapVenueType: function(e) {
    const typeId = e.currentTarget.dataset.id;
    this.setData({
      selectedType: typeId,
      loading: true
    });
    this.loadVenues();
  },
  
  // 切换排序方式
  onTapSortOption: function(e) {
    const sortId = e.currentTarget.dataset.id;
    this.setData({
      selectedSort: sortId,
      loading: true
    });
    this.loadVenues();
  },
  
  // 搜索输入
  onInputSearch: function(e) {
    this.setData({
      keyword: e.detail.value
    });
  },
  
  // 点击搜索按钮
  onTapSearch: function() {
    this.setData({ loading: true });
    this.loadVenues();
  },
  
  // 点击场馆项，进入时间段选择页面
  onTapVenue: function(e) {
    const id = e.currentTarget.dataset.id;
    const room = e.currentTarget.dataset.room || '';
    let url = `/pages/venue/timeslot?id=${id}&roomName=${room}`;
    
    // 如果有选择优惠券，则带上优惠券ID
    if (this.data.couponId) {
      url += `&coupon_id=${this.data.couponId}`;
    }
    
    wx.navigateTo({
      url: url
    });
  },
  
  // 下拉刷新
  onPullDownRefresh: function() {
    this.setData({ loading: true });
    this.loadVenues();
    wx.stopPullDownRefresh();
  },
  
  // 上拉加载更多
  onReachBottom: function() {
    // 实际项目中应该分页加载更多数据
    wx.showToast({
      title: '已加载全部场馆',
      icon: 'none'
    });
  }
})